package com.example.myapplication.Student;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.NetworkOnMainThreadException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.Adapter.SignInListAdapter;
import com.example.myapplication.Data.Course;
import com.example.myapplication.Data.CourseData;
import com.example.myapplication.Data.CourseDetailData;
import com.example.myapplication.Data.SignInList;
import com.example.myapplication.Data.SignInListData;
import com.example.myapplication.Data.UserData;
import com.example.myapplication.R;
import com.example.myapplication.Teacher.Tea_MyDetailActivity;
import com.example.myapplication.http.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class SignInNotFragment extends Fragment {
    private EditText editText;
    private String signCode;
    private Button btnBack;
    private Button btnSign;
    private JsonObject jsonObject;
    private SignInListData signInListData;//用于接收请求数据
    private SignInListAdapter adapter;
    private SignInList clickedItem;
    private ListView lvCourseList;//适配器显示视图
    private List<SignInList> signInList;
    private  SwipeRefreshLayout swipeRefreshLayout;

    private UserData userData;
    private CourseDetailData courseDetailData;
    private Dialog dialog;

    private final Gson gson = new Gson();
    //请求数据
    private int code;// 响应码
    private String msg;// 提示信息
    private Object data;// 实际数据

    protected View mView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }
    private void initView() {
        userData = (UserData) getActivity().getIntent().getSerializableExtra("userData");
        courseDetailData =(CourseDetailData) getActivity().getIntent().getSerializableExtra("courseDetailData");
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.fragment_sign_in_not, container, false);
            lvCourseList = mView.findViewById(R.id.list_courses);
            get();
        }

        // 如果 mView 不为空，表示视图已经创建
        return mView;
    }

    private void get(){
        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/sign/course/student/signList" +
                    "?courseId=" + courseDetailData.getId() +
                    "&status=0" +
                    "&userId=" + userData.getId();

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", "255cb403024d44f692620834ffc73623")
                    .add("appSecret", "12472e74638ef69e7412dbf2e818c2ae538d4")
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<Object>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("info", body);
            // 解析json串到自己封装的状态
            ResponseBody<Object> dataResponseBody = gson.fromJson(body,jsonType);
            Log.d("info", dataResponseBody.toString());

            // 获取响应的数据
            code = dataResponseBody.getCode();
            msg = dataResponseBody.getMsg();
            data = dataResponseBody.getData();

            handleResponse2();
        }
    };

    private void handleResponse2() {
        if (code == 200) {
            // 请求成功
            if (data != null) {

                jsonObject = gson.toJsonTree(data).getAsJsonObject();
                signInListData = gson.fromJson(jsonObject, SignInListData.class);
                signInList = signInListData.getRecords();

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initData();
                    }
                });
            } else {
                Log.d("返回空值", "data=null");
                Refresh();
            }
        } else {
            // 请求失败
            if (msg != null) {
                Log.d("请求失败", msg);
            }
        }
    }
    public void initData() {
        lvCourseList=(ListView)getActivity().findViewById(R.id.sign_in_not);
        lvCourseList.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        clickedItem = signInList.get(i);

                        dialog = new Dialog(getActivity());
                        dialog.setContentView(R.layout.activity_sign_in_detail); // 设置弹窗的自定义布局

                        editText = dialog.findViewById(R.id.editTextCode);
                        btnBack = dialog.findViewById(R.id.btnBack);
                        btnSign = dialog.findViewById(R.id.btnSign);
                        btnSign.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Sign();
                            }
                        });
                        btnBack.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss(); // 关闭弹窗
                            }
                        });
                        // 显示弹窗
                        dialog.show();
                    }
                }
        );

        adapter = new SignInListAdapter( getActivity(),
                R.layout.list_item_sign_in, signInList);
        lvCourseList.setAdapter(adapter);
        Refresh();
    }

    private void Sign(){
        signCode = String.valueOf(editText.getText());
        post2();

    }

    private void post2(){
        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/sign/course/student/sign";

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", "255cb403024d44f692620834ffc73623")
                    .add("appSecret", "12472e74638ef69e7412dbf2e818c2ae538d4")
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            // 请求体
            // PS.用户也可以选择自定义一个实体类，然后使用类似fastjson的工具获取json串
            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("signCode", signCode);
            bodyMap.put("userId", userData.getId());
            bodyMap.put("userSignId",clickedItem.getUserSignId());
            // 将Map转换为字符串类型加入请求体中
            String body = gson.toJson(bodyMap);

            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, body))
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback1);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    /**
     * 回调
     */
    private final Callback callback1 = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<Object>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("info", body);
            // 解析json串到自己封装的状态
            ResponseBody<Object> dataResponseBody = gson.fromJson(body,jsonType);
            Log.d("info", dataResponseBody.toString());

            code = dataResponseBody.getCode();
            msg = dataResponseBody.getMsg();
            data = dataResponseBody.getData();

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    handleResponse(); // 处理响应结果
                }
            });
        }
    };

    private void handleResponse() {
        if (code == 200) {
            Toast.makeText(getActivity(), "签到成功", Toast.LENGTH_LONG).show();
            dialog.dismiss();
        } else {
            if(msg != null) {
                Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //刷新
    public void Refresh() {
        //刷新列表
        swipeRefreshLayout = getActivity().findViewById(R.id.swipeRefreshLayout_sign_in_not);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                get();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }
}